﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Configuration;
using System.Text.RegularExpressions;
namespace XMK.AuthModule
{
    public class AuthModule : System.Web.IHttpModule, IRequiresSessionState
    {
       private static string FailUrl="";
       private static List<UrlPathRuleInfo> AuthRuleList = GetAuthSection();
        
        
        public void Init(HttpApplication context)
        {
            context.AcquireRequestState+=new EventHandler(context_AcquireRequestState);
        }


        void context_AcquireRequestState(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            // 获取Url
            string url = application.Request.Url.AbsolutePath;
            if (IsRequestUrlAuth(url))
            {
                if (HttpContext.Current.Session == null || HttpContext.Current.Session["_userid"] == null || string.IsNullOrEmpty(HttpContext.Current.Session["_userid"].ToString()))
                {
                    if(FailUrl=="")
                        HttpContext.Current.Response.End();
                    else
                    {
                        HttpContext.Current.Response.Redirect(FailUrl);
                    }
                }
            }
        }

        public void Dispose()
        {

        }

        /// <summary>
        /// 取配置节信息
        /// </summary>
        /// <returns></returns>
        private static List<UrlPathRuleInfo> GetAuthSection()
        {
            try
            {
                AuthSection _authsection = (AuthSection)System.Configuration.ConfigurationManager.GetSection("authSection");
                FailUrl = _authsection.FailUrl??"";
                AuthPathConnection ac = _authsection.AuthPathList;
                
                List<UrlPathRuleInfo> list = new List<UrlPathRuleInfo>();

                foreach (AuthPathInfoElement authinfo in ac)
                {
                    list.Add(new UrlPathRuleInfo() { PathInfo = authinfo.PathInfo, IsCheckSession = authinfo.IsCheckSession, IsCheckAuthorization = authinfo.IsCheckAuthorization, IsReg = authinfo.IsReg });
                }

                return list;
            }
            catch (Exception ex)
            {
                throw new Exception("读取认证模块配置异常" + ex.Message);
            }
        }

        /// <summary>
        /// 查找符合验证url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool IsRequestUrlAuth(string url) {
            if (string.IsNullOrEmpty(url)) return false;
            foreach (UrlPathRuleInfo rule in AuthRuleList) {
                return IsMatch(rule, url);
            }
            return false;
        }

        /// <summary>
        /// url是否匹配验证规则
        /// </summary>
        /// <param name="pathInfo"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool IsMatch(UrlPathRuleInfo pathInfo,string url) {
            if (pathInfo.IsCheckSession == false) return false;
            if (pathInfo.IsReg == false)
            {
                return url.ToLower().IndexOf(pathInfo.PathInfo.ToLower())>-1;
            }
            else
            {
                Regex reg = new Regex(pathInfo.PathInfo, RegexOptions.IgnoreCase);
                return reg.IsMatch(url);
            }
        }
    }
}
